import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class GenerateMemberServlet extends HttpServlet {

   String memberClasses[] = {"Person", "Student", "Athlete", "Faculty", "Staff"};
   Person members[] = {new Person(), new Student(), new Athlete(), new Faculty(), new Staff() };
   String headers[] = null;
   String rows[][] = new String [30][5];
   String number = "20", type = "Person";

   WebDocument doc = new WebDocument();

   HttpServletRequest request = null;

   public void doGet( HttpServletRequest req, HttpServletResponse resp ){

     try {
	resp.setContentType("text/html");
	PrintWriter out = resp.getWriter();

	request = req;

	generateMember();

	doc.clear();
	generateDoc();

	out.write(doc.toString());
	out.close();
     } catch (IOException e) { }
   }

   public void doPost( HttpServletRequest req, HttpServletResponse resp ) {
     try {
	resp.setContentType("text/html");
	PrintWriter out = resp.getWriter();

	request = req;

	generateMember();

	doc.clear();
	generateDoc();

	out.write(doc.toString());
	out.close();
     } catch (IOException e) { }
   }

   void generateDoc() {
	doc.startDocument("A Test Web Document").startCenter();
	
	doc.startForm("GenerateMemberServlet", "post");
	doc.addHeader(2, "HTML document generated by Java Servlet and WebDocument class");

	doc.addSelectbox("Member to generate", "type", memberClasses, type);
	doc.addSpaces(4);
	doc.addTextbox  ("Number to generate", "number", number);
	doc.addSpaces(4);
	doc.addCommandbox("Run");
	doc.addBreak().addBreak();

	// doc.addTable( request ).addBreak();
	doc.startFont("arial", "italic", "1", "red");
	doc.addItalicLine("Type : " + type ).addSpaces(4);
	doc.addItalicLine("Number: " + number).endFont().addBreak().addBreak();

	doc.addTable( headers, rows);

	doc.endForm().endCenter().endDocument();
   }

   void generateMember(  ) {
	int n = 20, idx = 0; 

	if ( request.getMethod().compareTo("GET") != 0 ) {
		n = Integer.parseInt( request.getParameter("number") );
		type = request.getParameter("type");
		number = request.getParameter("number");
		for ( idx = 0; idx < memberClasses.length; idx ++ )
			if ( memberClasses[idx].compareTo(type) == 0 ) break;
	}

	int cols = members[idx].getFieldCount();

	rows= new String[n][cols];
	headers = members[idx].getColumnTitles();
	for ( int i = 0; i < rows.length; i ++ ) {
		members[idx].generate();
		members[idx].getFields(rows[i]);
	}
  }

}
